package com.geelaro.register.controller;

import java.util.Collection;
import java.util.Iterator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.geelaro.register.domain.entity.Department;
import com.geelaro.register.domain.entity.Employee;
import com.geelaro.register.service.DepartmentService;
import com.geelaro.register.service.EmployeeService;


@Controller
public class EmploymentController {

	@Autowired
	private EmployeeService employeeService;

	@Autowired
	private DepartmentService departmentService;


	// 查询所有员工 ok
//	@GetMapping("/emps")
//	public String list(Model model) {
//		Collection<Employee> employees = employeeService.findAll();
//		model.addAttribute("emps", employees);
//		return "emp/list";
//	}
	
	@RequestMapping("/emps")
	public String list(Model model, @RequestParam(value = "pageNum", defaultValue = "0") int pageNum,
			@RequestParam(value = "pageSize", defaultValue = "5") int pageSize) {
		Page<Employee> employees = employeeService.findAll(pageNum, pageSize); 
		Iterator<Employee> u = employees.iterator();
		while (u.hasNext()) {
			System.out.println(u.next().toString());
		}
		model.addAttribute("emps", employees);
		return "emp/list";
	}
	
	// 员工删除 ok
	@GetMapping("/deleEmp/{id}")
	public String deleteEmployee(@PathVariable("id") Integer id) {
		employeeService.deleteById(id);
		return "redirect:/emps";
	}

	// 来到员工添加页面 ok
	@GetMapping("/emp")
	public String toAddPage(Model model) {
		// 得到部门表的所有数据
		Collection<Department> departments = departmentService.findAll();
		model.addAttribute("depts", departments);
		return "emp/add";
	}

	// 添加成功 ok 时间问题不对
	@PostMapping("/emp")
	public String addEmp(Employee employee) {
		employeeService.save(employee);
		return "redirect:/emps";
	}

	// 来到员工修改界面 ok
	@GetMapping("/emp/{id}")
	public String toEditPage(@PathVariable("id") Integer id, Model model) {
		Employee employee = employeeService.findEmployeeById(id);
		model.addAttribute("emp", employee);
		Collection<Department> departments = departmentService.findAll();
		model.addAttribute("depts", departments);
		return "emp/update";
	}

	// 修改成功，查出当前员工，在页面回显
	@RequestMapping(value = "/updateEmp", method = RequestMethod.POST)
	public String updateEmployee(Employee employee) {
		employeeService.save(employee);
		return "redirect:/emps";
	}

}
